<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#canvas{
				display: block;
				margin: 0 auto;
				box-shadow: 0 0 10px rgba(0,0,0,0.5);
			}
		</style>
	</head>
	<body>
		<canvas id="canvas"></canvas>
		<script src="../libs/utils.js"></script>
		<script type="text/javascript">
			// 箭头类
			class Arrow {
				constructor(props) {
				    this.w = 50
					this.h = 20
					this.x = 0;
					this.y=0;
					this.fillStyle = 'rgba(65,168,99,1)'
					this.strokeStyle = 'rgba(0,0,0,0)'
					this.rotation = 0;
					Object.assign(this,props)
					return this
				}
				createPath(ctx){
					var {w,h} = this
					
						ctx.beginPath()
						ctx.moveTo(-w/2,-h/2)
						ctx.lineTo(w/10,-h/2)
						ctx.lineTo(w/10,-h)
						// 
						ctx.lineTo(w/2,0)
						ctx.lineTo(w/10,h)
						ctx.lineTo(w/10,h/2)
						ctx.lineTo(-w/2,h/2)
						ctx.closePath()
					
				}
				render(ctx){
					var {strokeStyle,fillStyle,rotation,x,y} = this
					ctx.save()
						// 注意：先将位置移动到中心点，再进行旋转填充绘制。
						ctx.translate(x,y)
						// 旋转
						ctx.rotate(rotation)
						// 设置样式
						ctx.strokeStyle = strokeStyle
						ctx.fillStyle = fillStyle
						// 绘制路径
						this.createPath(ctx)
						
						// 描边
						ctx.stroke()
						// 填充
						ctx.fill()
						
					
					ctx.restore()
					return this
				}
			}
		</script>
		<script type="text/javascript">
			var canvas = document.querySelector('#canvas')
			var ctx = canvas.getContext('2d');
			
			var w = canvas.width = 500;
			var h = canvas.height = 300
			
			// 获取鼠标到canvas的距离
			var mouse = $C.getOffset(canvas)
			
			// 实例化渲染箭头
			var arrow = null;
			var speed = 2;
			
			(function move(){
				window.requestAnimationFrame(move)
				ctx.clearRect(0,0,w,h)
				drawSystem()
				drawArrowMove()
			})()
			// 绘制箭头并移动
			function drawArrowMove(){
				if(!arrow){
					arrow = new Arrow({x:w/2,y:h/2}).render(ctx);
				}
				// 获取鼠标的位置
				var {x,y} = mouse;
				var dy = y-arrow.y;
				var dx = x-arrow.x;
				var angle = Math.atan2(dy,dx)
				var vx = Math.cos(angle) * speed;
				var vy = Math.sin(angle) * speed;
				arrow.x +=vx;
				arrow.y+=vy;
				arrow.rotation = angle;
				arrow.render(ctx)
			}
			// 绘制坐标系
			function drawSystem(){
				ctx.save()
					ctx.beginPath()
					ctx.lineWidth = 1.5
					ctx.strokeStyle='red'
					ctx.moveTo(0,h/2)
					ctx.lineTo(w,h/2)
					ctx.moveTo(w/2,0)
					ctx.lineTo(w/2,h)
					ctx.stroke()
				ctx.restore()
			}
		</script>
	</body>
</html>
